package cn.wuqingna.legendgem.gui.gemmanager

import cn.wuqingna.legendgem.gem.GemManager.getItemGemGroup
import cn.wuqingna.legendgem.gem.GemManager.modifyLore
import cn.wuqingna.legendgem.gem.GemManager.saveGemGroup
import cn.wuqingna.legendgem.gui.Gui
import cn.wuqingna.legendgem.loader.GemLoader
import taboolib.module.nms.ItemTag
import taboolib.module.ui.ClickEvent
import taboolib.platform.util.hasLore
import taboolib.platform.util.isNotAir
import taboolib.platform.util.sendLang
import taboolib.platform.util.takeItem

object EmbedManager {

    fun embedManager(event: ClickEvent, gui: Gui, tag: ItemTag) {
        val item = event.clickEvent().currentItem
        val deep = tag.getDeep("legendGem.gem-key")
        if (deep != null && gui.useItem.isNotAir()) {
            val fileName = gui.config.file!!.name.replace(".yml", "")
            val gem = GemLoader.gems[deep.asString()]!!
            if (!gem.options.selectGui.contains(fileName) && gem.options.selectGui.size > 0) {
                event.clicker.sendLang("select-gui")
                return
            }
            if (item.hasLore()) {
                val group = gui.useItem.getItemGemGroup()

                group.forEach {
                    if (it.embed(gui, item, event.clicker)) {
                        gui.useItem.modifyLore(it.cacheLore, it.refreshLore())
                        it.refreshCacheLore()
                        event.clicker.inventory.takeItem(1) { it.isSimilar(item) }
                        return@forEach
                    } else {
                        return@forEach
                    }
                }
                gui.useItem.saveGemGroup(group)
                gui.refreshUseItem(event.clicker)
                LuckManager.clear(event.clicker, gui)
            }
        }
    }

}